package com.app.business.service;

import com.app.business.model.AzProject;
import com.app.business.model.Contract;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.dataType.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Query;
import java.util.List;
import java.util.Map;

/**
 * 推送到main系统专用
 * Created by ddz on 2021/5/31.
 */
@SuppressWarnings(value = "ALL")
@Service
public class StatisticsForMainService extends JpaBaseDao<Contract, Integer> {
    @Autowired
    private ContractService contractService;
    @Autowired
    private HouseService houseService;
    @Autowired
    private CarLotService carLotService;
    @Autowired
    private StorageRoomService storageRoomService;
    @Autowired
    private AzProjectService azProjectService;
    @Autowired
    private ZsProjectService zsProjectService;
    @Autowired
    private DataDictService dataDictService;

    /**
     * 所有征收项目得到征收信息统计
     *
     * @param azProjectId
     * @return
     */
    public List<Map> getDataForMain() {
        List<Map> resultList = Lists.newLinkedList();
        Map<String, String> townMap = dataDictService.getMapByParentNameForValue_Name("乡镇");

        List<AzProject> azProjectList = this.azProjectService.azProjectList();
        Map itemMap = Maps.newLinkedHashMap();//循环存放每条数据
        if (!azProjectList.isEmpty()) {
            Map<String, Map<String, Map>> contractSumMap = this.getContractSumByAzProjectMap();
            /*为方便统计使用，已安置数据以负数进行计算*/
            for (AzProject azProject : azProjectList) {
                if (CollectionUtils.isNotEmpty(contractSumMap.get(String.valueOf(azProject.getId())))) {
                    Map<String, Map> newOldStatusMap = contractSumMap.get(String.valueOf(azProject.getId()));
                    for (String newOldStatus : newOldStatusMap.keySet()) {
                        itemMap = null;
                        itemMap = Maps.newLinkedHashMap();
                        itemMap.put("town", StringUtils.getNotNull(townMap.get(azProject.getTown()))); //乡镇
                        itemMap.put("databaseName", "fjqz_xf"); //项目数据库名称
                        itemMap.put("resettlementName", azProject.getProjectName()); //安置区名称
                        itemMap.put("haveNumArea", "-" + String.valueOf(newOldStatusMap.get(newOldStatus).get("limitHouseAreaTotal"))); //选房顺序号的安置面积
                        itemMap.put("chooseHouseAreaTotal", "-" + String.valueOf(newOldStatusMap.get(newOldStatus).get("chooseHouseAreaTotal"))); //选房顺序号的选房面积
                        itemMap.put("chooseNumTotal", "-" + String.valueOf(newOldStatusMap.get(newOldStatus).get("chooseHouseNumCount")));//对应的选房顺序号个数
                        itemMap.put("projectNum", "-" + String.valueOf(newOldStatusMap.get(newOldStatus).get("zsProjectCount"))); //对应的征收项目个数
                        itemMap.put("newOldStatus", newOldStatusMap.get(newOldStatus).get("newOldStatus"));  //所属系统  1、19年前老系统；2、19年后新系统
                        itemMap.put("numOutSignProjectNum", 0);
                        itemMap.put("numOutSignChooseNum", 0);
                        itemMap.put("numInSignProjectNum", 0);
                        itemMap.put("numInSignChooseNum", 0);
                        itemMap.put("advanceProjectNum", 0);
                        itemMap.put("advanceChooseNum", 0);
                        resultList.add(itemMap);
                    }
                }
            }
        }
        return resultList;
    }

    /**
     * 所有征收项目得到征收信息统计
     *
     * @return
     */
    public Map<String, Map<String, Map>> getContractSumByAzProjectMap() {

        StringBuffer sql = new StringBuffer(" SELECT ha.azProjectId AS azProjectId,c.new_old_status AS newOldStatus ,");
        sql.append(" COUNT(DISTINCT(c.id)) AS chooseHouseNumCount,COUNT(DISTINCT(zsp.id)) AS zsProjectCount, ");

        sql.append(" SUM(CASE WHEN c.is_Ji_Suan =1  THEN (IFNULL(c.property_change_area,0) + IFNULL(c.care_buy_area1,0) + ");
        sql.append(" IFNULL(c.care_buy_area2,0)+ IFNULL(c.care_buy_area3,0)+ IFNULL(c.care_buy_area4,0)+ IFNULL(c.care_buy_area5,0)+ ");
        sql.append(" IFNULL(c.care_buy_area6,0)+ IFNULL(c.care_buy_area7,0)+ IFNULL(c.care_buy_area8,0)+ IFNULL(c.adjust_area,0)) ELSE 0 END)+ ");
        sql.append(" SUM(CASE WHEN c.is_Ji_Suan IS NOT NULL AND c.is_Ji_Suan != 1 THEN IFNULL(c.choose_House_Area_Total,0) ELSE 0 END) AS limitHouseAreaTotal, ");
        sql.append(" SUM(CASE WHEN c.choose_house_status = 2 THEN IFNULL(c.choose_House_Area_Total,0) ELSE 0 END) AS chooseHouseAreaTotal  ");
        sql.append(" FROM contract c INNER JOIN zs_project zsp ON c.zs_project_id = zsp.id,");
        sql.append(" (SELECT DISTINCT(h.contract_id) AS contractId,h.az_project_id AS azProjectId FROM house h) ha");
        sql.append(" WHERE ha.contractId=c.id");
        sql.append(" GROUP BY ha.azProjectId,c.new_old_status ORDER BY ha.azProjectId,c.new_old_status");

        Query query = this.entityManager.createNativeQuery(sql.toString());
        List<Map> mapList = query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        Map<String, Map<String, Map>> contractSumMap = Maps.newHashMap();
        Map<String, Map> newOldStatusMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map map : mapList) {
                String newOldStatus = map.get("newOldStatus").toString();
                String azProjectId = map.get("azProjectId").toString();
                newOldStatusMap = contractSumMap.get(azProjectId) == null ? Maps.newHashMap() : contractSumMap.get(azProjectId);
                newOldStatusMap.put(newOldStatus, map);
                contractSumMap.put(azProjectId, newOldStatusMap);
            }
        }
        return contractSumMap;
    }

}

